package com.guguskins.back.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

public class MessageMD5 {

    public static String MD5(String s) {
        char[] hexdigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

        try {
            byte[] strTemp = s.getBytes();
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexdigits[byte0 >>> 4 & 0xf];
                str[k++] = hexdigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    //盐，用于混交md5
    private static final String SLAT = "&%5123***&&%%$$#@";

    public static String encrypt(String dataStr) {
        try {
            dataStr = dataStr + SLAT;
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.update(dataStr.getBytes(StandardCharsets.UTF_8));
            byte[] s = m.digest();
            StringBuilder result = new StringBuilder();
            for (byte b : s) {
                result.append(Integer.toHexString((0x000000FF & b) | 0xFFFFFF00).substring(6));
            }
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 判断用户密码是否正确
     *
     * @param newPasswd 用户输入的密码
     * @param oldPasswd 正确密码
     */
    public static boolean checkPassword(String newPasswd, String oldPasswd) {
        return encrypt(newPasswd).equals(oldPasswd);
    }

    public static void main(String[] args) {
        String asdasdassd = encrypt("asdasdassd");
        System.err.println(asdasdassd);
    }
}
